package net.easyjava.test.aws;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.*;
import net.easyjava.tools.security.encrypt.MD5Tools;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wxnacy on 16/11/24.
 */
public class SQSDemo {
    public static final String QUEUE_EASYJAVA_TEST = "easyjava-test";
    public static final String QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/053227996260/easyjava-test";
    private static AWSCredentials credentials;
    private static AmazonSQSClient sqs;

    public SQSDemo() {
        init();
    }

    public static void main(String[] args) {
        //初始化信息
        init();
        //创建有序队列
//        createFifoQueue();
        //创建队列
//        String queueUrl = createQueue("queue-1");
//        createQueue("queue-2");
        //删除队列
//        delQueue("https://sqs.us-east-1.amazonaws.com/053227996260/sdsd");
        //列出队列列表
//        listQueues();
        //发送消息
//        sendMessage(QUEUE_URL);
        //接收消息
        while(true){
            String headle = receiveMessage("https://sqs.us-east-1.amazonaws.com/053227996260/queue-1");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //删除消息
//        delMessage(QUEUE_URL,headle);
    }



    /**
     * 初始化信息
     */
    private static void init(){

        try{
            credentials = new BasicAWSCredentials(AWSConstants.KEY_ID,AWSConstants.KEY_SECRET);
            sqs = new AmazonSQSClient(credentials);
        }catch(Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 创建有序队列
     */
    private static void createFifoQueue(){
        System.out.println("Creating a new Amazon SQS FIFO queue called MyFifoQueue.fifo.\n");
        Map<String, String> attributes = new HashMap<String, String>();
        // A FIFO queue must have the FifoQueue attribute set to True
        attributes.put("FifoQueue", "true");
        // Generate a MessageDeduplicationId based on the content, if the user doesn't provide a MessageDeduplicationId
        attributes.put("ContentBasedDeduplication", "true");
        // The FIFO queue name must end with the .fifo suffix
        CreateQueueRequest createQueueRequest = new CreateQueueRequest("easyjava.fifo").withAttributes(attributes);
        String myQueueUrl = sqs.createQueue(createQueueRequest).getQueueUrl();

//        sqs.createQueue("easyjava");
        System.out.println("myQueueUrl = " + myQueueUrl);
    }
    private static String createQueue(String queueName){
        System.out.println("Creating a new Amazon SQS FIFO queue called MyFifoQueue.fifo.\n");
        String myQueueUrl = sqs.createQueue(queueName).getQueueUrl();

//        sqs.createQueue("easyjava");
        System.out.println("myQueueUrl = " + myQueueUrl);

        return myQueueUrl;
    }



    /**
     * 列出队列列表
     */
    private static void listQueues(){
        System.out.println("Listing all queues in your account.\n");
        for (String queueUrl : sqs.listQueues().getQueueUrls()) {
            System.out.println("  QueueUrl: " + queueUrl);
        }
    }

    /**
     * 发送消息
     * @param queueUrl
     */
    private static void sendMessage(String queueUrl){
        // Send a message
        System.out.println("Sending a message to queue\n");
        SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, "This is my message text.");
        SendMessageResult sendMessageResult = sqs.sendMessage(sendMessageRequest);
        String sequenceNumber = sendMessageResult.getSequenceNumber();
        String messageId = sendMessageResult.getMessageId();
        System.out.println("SendMessage succeed with messageId " + messageId + ", sequence number " + sequenceNumber + "\n");

    }

    private static void sendFifoMessage(String queueUrl){
        // Send a message
        System.out.println("Sending a message to MyFifoQueue.fifo.\n");
        SendMessageRequest sendMessageRequest = new SendMessageRequest(queueUrl, "This is my message text.");
        // You must provide a non-empty MessageGroupId when sending messages to a FIFO queue
        sendMessageRequest.setMessageGroupId("messageGroup1");
        // Uncomment the following to provide the MessageDeduplicationId
        //sendMessageRequest.setMessageDeduplicationId("1");
        SendMessageResult sendMessageResult = sqs.sendMessage(sendMessageRequest);
        String sequenceNumber = sendMessageResult.getSequenceNumber();
        String messageId = sendMessageResult.getMessageId();
        System.out.println("SendMessage succeed with messageId " + messageId + ", sequence number " + sequenceNumber + "\n");

    }

    /**
     * 接收消息
     * @param queueUrl
     */
    private static String receiveMessage(String queueUrl){
        // Receive messages
        System.out.println("Receiving messages from MyFifoQueue.fifo.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
        // Uncomment the following to provide the ReceiveRequestDeduplicationId
        //receiveMessageRequest.setReceiveRequestAttemptId("1");
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());

            System.out.println("MD5Tools.getInstan:" + MD5Tools.getInstance().encryptToString(message.getBody()));
            for (Map.Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }

        if(messages != null && messages.size()>0){
            return messages.get(0).getReceiptHandle();
        }
        return null;
    }
    public List<Message> receiveMessageFromTopic(String queueUrl){
        // Receive messages
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl);
        // Uncomment the following to provide the ReceiveRequestDeduplicationId
        //receiveMessageRequest.setReceiveRequestAttemptId("1");
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        return messages;
    }

    /**
     * 删除消息
     * @param queueUrl
     * @param headle
     */
    private static void delMessage(String queueUrl,String headle){
        System.out.println("SQSDemo.delMessage");
        DeleteMessageResult result = sqs.deleteMessage(new DeleteMessageRequest(queueUrl, headle));
        System.out.println("result.getSdkResponseMetadata() = " + result.getSdkResponseMetadata());
        System.out.println("result.toString() = " + result.toString());
    }

    public String delMsg(String queueUrl,String headle){
        DeleteMessageResult result = sqs.deleteMessage(new DeleteMessageRequest(queueUrl, headle));
        return result.toString();
    }


    /**
     * 删除队列
     * @param queueUrl
     */
    private static void delQueue(String queueUrl){
        DeleteQueueResult result = null;
        try{
            result = sqs.deleteQueue(new DeleteQueueRequest(queueUrl));
            System.out.println("result.getSdkResponseMetadata() = " + result.getSdkResponseMetadata());
        }catch(Exception e){
            System.out.println("e.getMessage() = " + e.getMessage());
//            e.printStackTrace();
        }
    }


    private static void dd(String myQueueUrl){
        // List queues

        System.out.println();


        // Receive messages
        System.out.println("Receiving messages from MyFifoQueue.fifo.\n");
        ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(myQueueUrl);
        // Uncomment the following to provide the ReceiveRequestDeduplicationId
        //receiveMessageRequest.setReceiveRequestAttemptId("1");
        List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
        for (Message message : messages) {
            System.out.println("  Message");
            System.out.println("    MessageId:     " + message.getMessageId());
            System.out.println("    ReceiptHandle: " + message.getReceiptHandle());
            System.out.println("    MD5OfBody:     " + message.getMD5OfBody());
            System.out.println("    Body:          " + message.getBody());
            for (Map.Entry<String, String> entry : message.getAttributes().entrySet()) {
                System.out.println("  Attribute");
                System.out.println("    Name:  " + entry.getKey());
                System.out.println("    Value: " + entry.getValue());
            }
        }
        System.out.println();

        // Delete the message
        System.out.println("Deleting the message.\n");
        String messageReceiptHandle = messages.get(0).getReceiptHandle();
        sqs.deleteMessage(new DeleteMessageRequest(myQueueUrl, messageReceiptHandle));


        // Delete the queue
        System.out.println("Deleting the queue.\n");
        sqs.deleteQueue(new DeleteQueueRequest(myQueueUrl));
    }








}
